//
//  HttpRequestPlatformInterface.cpp
//  EZC_Library
//
//  Created by ellzu on 14-9-23.
//  Copyright (c) 2014年 ellzu. All rights reserved.
//

#include "HttpRequestPlatformInterface.h"
#include "HttpRequest.h"
#include "HttpResponse.h"

using namespace EZHttp;

HttpRequestPlatformInterface::HttpRequestPlatformInterface()
{
    _ownRequest = 0;
    _alreadyCallPercent = 0;
}
HttpRequestPlatformInterface::~HttpRequestPlatformInterface()
{
    
}

std::map<std::string, std::string>* HttpRequestPlatformInterface::requestValues()
{
    return &(_ownRequest->_requestValues);
}

void HttpRequestPlatformInterface::response_setContentLen(size_t len)
{
    _ownRequest->response()->setContentLen(len);
    _contentLen = len;
}

void HttpRequestPlatformInterface::setOwnRequest(HttpRequest* request)
{
    _ownRequest = request;
}
HttpRequest* HttpRequestPlatformInterface::ownRequest()
{
    return _ownRequest;
}

void HttpRequestPlatformInterface::onHttpRequestResponseHeader()
{
    HttpRequestDelegate *delegate = _ownRequest->delegate();
    if (delegate) {
        delegate->onHttpRequestResponseHeader(_ownRequest);
    }
    _alreadyCallPercent = 0;
    _curLen = 0;
}
size_t HttpRequestPlatformInterface::onHttpRequestReciveContent(unsigned char* data,size_t dataLen)
{
    HttpRequestDelegate *delegate = _ownRequest->delegate();
    size_t writesize = 0;
    if (delegate) {
        writesize = delegate->onHttpRequestReciveContent(_ownRequest, data, dataLen, _contentLen);
    }
    if (writesize==0) {
        writesize = _ownRequest->response()->appendBuffer(data, dataLen);
    }
    
    _curLen += writesize;
    
    if (delegate) {
        size_t totalLen = _contentLen;
        unsigned int currentprecent = (_curLen*1.0 / totalLen) * _ownRequest->progressCount();
        if (currentprecent != _alreadyCallPercent) {
            delegate->onHttpRequestProgress(_ownRequest);
        }
        _alreadyCallPercent = currentprecent;
    }
    
    return writesize;
}

void HttpRequestPlatformInterface::onHttpRequestSuccess()
{
    HttpRequestDelegate *delegate = _ownRequest->delegate();
    if (delegate) {
        delegate->onHttpRequestSuccess(_ownRequest);
    }
}
void HttpRequestPlatformInterface::onHttpRequestFail()
{
    HttpRequestDelegate *delegate = _ownRequest->delegate();
    if (delegate) {
        delegate->onHttpRequestFail(_ownRequest);
    }
}




